import type { ToolItem } from './types';

// 全局工具配置对象
let globalToolConfig: Record<string, ToolItem> = {};

// 注册单个工具
function registerTool(tool: ToolItem) {
  if (!tool.id) {
    throw new Error('Tool must have an id');
  }
  
  if (!tool.name) {
    throw new Error('Tool must have a name');
  }
  
  if (!tool.icon) {
    throw new Error('Tool must have an icon');
  }
  
  if (typeof tool.onClick !== 'function') {
    throw new Error('Tool must have an onClick function');
  }
  
  // 注册工具
  globalToolConfig[tool.id] = {
    ...tool
  };
  
  return globalToolConfig;
}

// 注册多个工具
function registerTools(tools: ToolItem[]) {
  tools.forEach(tool => {
    registerTool(tool);
  });
  
  return globalToolConfig;
}

// 获取单个工具
function getTool(toolId: string): ToolItem | undefined {
  return globalToolConfig[toolId];
}

// 获取所有工具
function getAllTools(): Record<string, ToolItem> {
  return { ...globalToolConfig };
}

// 获取工具列表
function getToolList(): ToolItem[] {
  return Object.values(globalToolConfig);
}

// 根据组获取工具
function getToolsByGroup(group: string): ToolItem[] {
  return Object.values(globalToolConfig).filter(tool => tool.group === group);
}

// 移除单个工具
function unregisterTool(toolId: string): boolean {
  if (toolId in globalToolConfig) {
    delete globalToolConfig[toolId];
    return true;
  }
  return false;
}

// 移除多个工具
function unregisterTools(toolIds: string[]): boolean {
  let allRemoved = true;
  toolIds.forEach(toolId => {
    if (!unregisterTool(toolId)) {
      allRemoved = false;
    }
  });
  return allRemoved;
}

// 清空所有工具
function clearTools(): void {
  globalToolConfig = {};
}

// 导出工具函数
export {
  registerTool,
  registerTools,
  getTool,
  getAllTools,
  getToolList,
  getToolsByGroup,
  unregisterTool,
  unregisterTools,
  clearTools
};

// 默认导出
export default {
  registerTool,
  registerTools,
  getTool,
  getAllTools,
  getToolList,
  getToolsByGroup,
  unregisterTool,
  unregisterTools,
  clearTools
};